import os

import requests


def upload_image(dir_path, url):
    """
    上传图片到指定的URL

    :param dir_path: 图片文件夹的本地路径
    :param url: 上传图片的目标URL
    :return: 服务器响应列表
    """
    # 检查目录是否存在
    if not os.path.isdir(dir_path):
        return "目标不存在"

    responses = []
    # 遍历目录中的所有文件
    for filename in os.listdir(dir_path):
        file_path = os.path.join(dir_path, filename)

        # 检查文件是否为图片(可以根据文件扩展名进行判断)
        if os.path.isfile(file_path) and filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')):
            try:
                with open(file_path, 'rb') as file:
                    files = {'file': (filename, file)}
                    response = requests.post(url, files=files)
                    responses.append(response.text)
                    print(f"上传成功: {filename}")
            except Exception as e:
                print(f"上传失败: {filename}")
                print(f"错误信息: {str(e)}")
    return responses

if __name__ == '__main__':
    # 图片的本地路径
    dir_path = r'C:\Users\admin\Desktop\1'
    # 上传图片的目标URL
    upload_url = 'https://label.idimage.com.cn/api/label/upload/img'

    result = upload_image(dir_path, upload_url)
    print("上传结果:", result)